'use strict';
/**
 * controllers for process
 */
app.controller('processDefinedCtrl', ["$scope", "$stateParams", "$modal", "Restangular", "SweetAlert", "api_bpm", function($scope, $stateParams, $modal, Restangular, SweetAlert, api_bpm) {

    console.log($stateParams);
    if (angular.isString($stateParams.modelId) && $stateParams.modelId != "") {
        $scope.modelId = $stateParams.modelId;
        api_bpm.modelsource($stateParams.modelId).then(function(data) {
            if (data) {
                var myData = Restangular.stripRestangular(data);
                if (myData.data) {
                    bpmnJS.openDiagram(myData.data);
                }
            }
        });
    }

    var bpmnJS = new window.BpmnJS({
        container: angular.element('#js-drop-zone'),
        canvas: angular.element('#js-canvas'),
        propertiesPanel: angular.element('#js-properties-panel')
    });

    $scope.createNewDiagram = function() {
        bpmnJS.createNewDiagram();
    }

    $scope.openDiagram = function(xml) {
        bpmnJS.openDiagram(xml);
    }

    var setEncoded = function(link, name, data) {
        var encodedData = encodeURIComponent(data);

        if (data) {
            link.addClass('active').attr({
                'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
                'download': name
            });
        } else {
            link.removeClass('active');
        }
    }

    $scope.downloadDiagram = function() {
        bpmnJS.saveDiagram(function(err, xml) {
            setEncoded(angular.element('#js-download-diagram'), 'diagram.bpmn', err ? null : xml);
        });
    }

    $scope.deploy = function() {
        bpmnJS.saveDiagram(function(err, xml) {
            if (err) {

            } else {
                var data = {
                    'json_xml': xml
                };
                if (angular.isDefined($scope.modelId)) {
                    data.modelId = $scope.modelId;
                    api_bpm.deploy(data).then(function(response) {
                        console.log(response);
                    });
                } else {
                    var modalInstance = $modal.open({
                        templateUrl: 'assets/views/process/tpl/modal_process.html',
                        controller: function($scope, $modalInstance, title, Alert) {
                            $scope.title = title;
                            $scope.ok = function() {
                                if (angular.isUndefined($scope.data.key) || $scope.data.key == "") {
                                    Alert.swal({
                                        title: "流程信息不能为空",
                                        text: "请将相关信息填写完全!",
                                        type: "error"
                                    });
                                } else {
                                    $modalInstance.close($scope.data);
                                }
                            }
                            $scope.cancel = function() {
                                $modalInstance.dismiss('cancel');
                            };
                        },
                        size: 'sm',
                        resolve: {
                            title: function() {
                                return "配置流程属性";
                            },
                            Alert: function() {
                                return SweetAlert;
                            }
                        }
                    });
                    modalInstance.result.then(function(processData) {
                        if (processData) {
                            angular.extend(processData, data);
                            api_bpm.deploy(data).then(function(response) {
                                console.log(response);
                            });
                        } else {

                        }
                    });
                }
            }
        });
    }

    $scope.save = function() {
        bpmnJS.saveDiagram(function(err, xml) {
            if (err) {

            } else {
                var data = {
                    'json_xml': xml
                };
                if (angular.isDefined($scope.modelId)) {
                    var modelId = $scope.modelId;
                    api_bpm.savemodel(modelId, data).then(function(response) {
                        console.log(response);
                    });
                } else {
                    console.log()
                }

            }
        });
    }



    if (!window.FileList || !window.FileReader) {
        window.alert(
            'Looks like you use an older browser that does not support drag and drop. ' +
            'Try using Chrome, Firefox or the Internet Explorer > 10.');
    } else {
        bpmnJS.registerFileDrop(angular.element('#js-drop-zone'), bpmnJS.openDiagram);
    }
}]);


app.controller('processDefinedListCtrl', ["$scope", "$state", "$timeout", "$interval", "SweetAlert", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_bpm", function($scope, $state, $timeout, $interval, SweetAlert, uiGridConstants, uiGridGroupingConstants, Restangular, api_bpm) {
    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = true;
    $scope.gridOptions.enableGridMenu = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = true;
    $scope.gridOptions.fastWatch = true;

    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };

    $scope.gridOptions.columnDefs = [
        { name: '操作', cellTemplate: '<a class="btn btn-sm btn-info " ng-click="grid.appScope.pdList.selectRowFunction(row.entity)"><i class="fa fa-pencil-square-o"/></a><a class="btn btn-sm btn-warning" ng-click="grid.appScope.pdList.removeRowFunction(row.entity)"><i class="fa fa-trash"/></a>', enableFiltering: false },
        { name: 'id', width: 100, enableFiltering: false },
        { name: 'deploymentId', displayName: '部署Id', width: 100, enableFiltering: false },
        { name: 'name', displayName: '名称', width: 100 },
        { name: 'key', displayName: 'KEY', width: 200 },
        { name: 'version', displayName: '版本号', width: 100 },
        { name: '最后更新时间', field: 'lastUpdateTime', cellFilter: 'date', width: 150, type: 'date', enableFiltering: false },
        { name: '创建时间', field: 'createTime', cellFilter: 'date', width: 150, type: 'date', enableFiltering: false }
    ];

    $scope.gridOptions.importerDataAddCallback = function(grid, newObjects) {
        $scope.myData = $scope.myData.concat(newObjects);
    };

    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;
        //gridApi.selection.on.rowSelectionChanged($scope, selectRowFunction);
    };

    this.selectRowFunction = function(data) {
        console.log(data);
        $state.go('app.process.modeler', { modelId: data.id });
    };

    this.removeRowFunction = function(data) {
        //TODO $translate('key')
        SweetAlert.swal({
            title: "确认删除?",
            text: "删除以后，你将不能恢复该数据!",
            type: "warning",
            cancelButtonText: "取消",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认删除!"
        }, function(isConfirm) {
            if (isConfirm) {
                api_bpm.removemodel(data.id).then(function(response) {
                    if (response) {
                        $scope.refreshData();
                        SweetAlert.swal({
                            title: "删除成功!",
                            confirmButtonColor: "#007AFF"
                        });
                    }
                });
            } else {

            }

        });

    }


    $scope.callsPending = 0;

    var i = 0;
    $scope.refreshData = function() {
        $scope.myData = [];

        var start = new Date();
        var sec = $interval(function() {
            $scope.callsPending++;
            api_bpm.list().then(function(data) {
                $scope.callsPending--;
                var myData = Restangular.stripRestangular(data);
                $scope.myData = myData.data;
            });
        }, 200, 10);

        var timeout = $timeout(function() {
            $interval.cancel(sec);
            $scope.left = '';
        }, 2000);

        $scope.$on('$destroy', function() {
            $timeout.cancel(timeout);
            $interval.cancel(sec);
        });
    };

    $scope.refreshData();

}]);